<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo21-1</title>
    <link rel="stylesheet" href="../js/lib/ol4.6.4/ol.css" type="text/css">
    <link rel="stylesheet" href="../css/demo21.css" type="text/css">
</head>
<body>
<div id="map"></div>
<ul class="tool-box" id="tools">
    <li type="Point" class="draw-btn">点</li>
    <li type="LineString" class="draw-btn">线</li>
    <li type="Polygon" class="draw-btn">面</li>
    <li type="Edit" class="draw-btn">编辑</li>
</ul>
<div class="edit-info">
    <input id="name" type="text" placeholder="名称">
    <input id="submit" type="button"  value="确定">
    <div class="edit-tools">
        <input id="editName" type="text" placeholder="编辑">
        <input id="editSave" type="button"  value="保存">
        <input id="editClose" type="button"  value="关闭">
    </div>
</div>
<script src="../js/lib/ol4.6.4/ol.js"></script>
<script src="../js/lib/jquery/jquery-3.3.1.min.js"></script>
<script>
    var map;
    var wktFormat = new ol.format.WKT();
    var element = $("<ul/>").addClass("edit-tools");
    var source = new ol.source.Vector({
        features: []
    });

    var vector = new ol.layer.Vector({
        source: source,
        style: function (feature) {
            return styleFunction(feature, false);
        }
    });

    map = new ol.Map({
        controls: ol.control.defaults({
            attribution: false
        }),
        target: 'map',
        layers: [
            getTilelayer('vec_w'),
            getTilelayer('cva_w'),
            vector
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([98.633, 31.607]),
            zoom: 4,
            minZoom: 0,
            maxZoom: 18
        })
    });

    addFeatures();

    var draw,select,edit;

    select = new ol.interaction.Select({
        layers:[vector],
        style: function (feature) {
            return styleFunction(feature, true);
        }
    });
    edit = new ol.interaction.Modify({
        features: select.getFeatures()
    });

    select.on("select", function (e) {
        var features = e.selected;
        if (features.length > 0) {
            startEdit();
        } else {
            deSelectEvt();
        }
    });

    map.addInteraction(select);
    map.addInteraction(edit);
    select.setActive(false);
    edit.setActive(false);

    $("#tools > li").on("click",function () {
        var _type = $(this).attr("type");
        var isActive=$(this).hasClass("active")
        if (_type === "Edit") {
            if (isActive) {
                $(this).removeClass("active");
                select.setActive(false);
                edit.setActive(false);
                $(".edit-info").hide();
            } else {
                $(this).addClass("active");
                select.setActive(true);
                edit.setActive(true);
            }
        } else {
            if (edit.getActive()){
                if (confirm("正在编辑中，是否保存当前编辑？")){
                    if($("#editName").val() === ""){
                        $(".toolEdit").addClass("active");
                        console.log($("#editName").val());
                        alert("保存信息不完整，请检查后再保存！");
                    } else {
                        saveEdit();
                        $(this).addClass("active");
                        addDrawTool(_type);
                    }
                }
            } else {
                $(this).addClass("active");
                addDrawTool(_type);
            }
            // $(".draw-btn").removeClass("active");
            // $(this).addClass("active");
            // addDrawTool(_type);
        }
    })

    $("#submit").on("click",function () {
        var name = $("#name").val();
        var selectFeatures = select.getFeatures();
        var selectFeature = selectFeatures.item(0);
        var WKTGeo = wktFormat.writeGeometry(selectFeature.getGeometry());//坐标系转换为4326
        var paras = {
            name: name,
            geom: WKTGeo + ''
        };
        $.get("edit/add", paras, function () {
            select.getFeatures().clear();
            select.setActive(false);
            edit.setActive(false);
            addFeatures();
        })
    })

    map.on('click',function (evt) {
        if (!map.hasFeatureAtPixel(evt.pixel)) {
            edit.setActive(false);
        } else {
            edit.setActive(true);
        }
    });
    map.on('pointermove', function(evt) {
        if(map.hasFeatureAtPixel(evt.pixel)){
            $(map.getTargetElement()).css("cursor", "pointer");
        }else{
            $(map.getTargetElement()).css("cursor", "default");
        }
    });

    $("#editClose").on("click", function (){
        deSelectEvt();
    });

    $("#editSave").on("click",function () {
        var selectFeatures=select.getFeatures();
        if($("#editName").val() === "" || selectFeatures.getLength() === 0){
            console.log($("#editName").val(),selectFeatures.getLength());
            alert("保存信息不完整，请检查后再保存！");
        } else {
            if(confirm("确定保存该条记录吗？")){
                saveEdit();
            } else {
                return;
            }
        }
    });

    function addDrawTool(type) {
        if (draw) map.removeInteraction(draw);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            stopClick: true,
            freehand: false//自由手绘
        });
        map.addInteraction(draw);

        //绘制结束
        draw.on("drawend", function (evt) {
            draw.setActive(false);
            select.setActive(true);
            var feature = evt.feature;
            feature.attr = {
                id:"",
                name: "",
            };
            select.getFeatures().insertAt(0, feature);
            startEdit();
        });
    }

    function saveEdit() {
        var selectFeatures = select.getFeatures();
        var selectFeature = selectFeatures.item(0);
        selectFeature.attr.name = $("#editName").val();
        var wkt= wktFormat.writeFeature(selectFeature);
        console.log(wkt);

        $(".edit-info").hide();
        edit.setActive(false);
        select.setActive(false);
        select.getFeatures().clear();
        element.children().removeClass("active");

        $("#editName").val("");
    }
    
    function startEdit(){
        var feture = select.getFeatures().item(0);
        var attr = feture.attr;
        $("#editName").val(attr.name);
        $(".edit-info").show();
        edit.setActive(true);
    }

    function deSelectEvt() {
        if(edit.getActive()){
            if(confirm("正在编辑，是否保存？")){
                saveEdit();
            }
        } else {
            edit.setActive(false);
            $(".edit-info").hide();
        }
    }
    
    function addFeatures(){
        source.clear();
        $.get('edit/query', {name:null},function (result){
            var length=0;
            var features = [];
            if (result.data)
                length=result.data.length
            for (var i=0;i<length;i++) {
                var _r = result.data[i];
                var feature = wktFormat.readFeature(_r.geom);
                feature.getGeometry()//transform("EPSG:4326", "EPSG:3857");
                feature.attr = {
                    id: _r.id,
                    name: _r.name
                };
                features.push(feature);
            }
            source.addFeatures(features);
        })
    }

    function styleFunction(feature, isSelect) {
        var stroke = new ol.style.Stroke({
            color: 'black',
            width: 2
        });
        var fill = new ol.style.Fill({
            color: 'red'
        });
        var _name = "",
            _color = "#ccc";
        if (isSelect) {
            _name = feature.get("name");
            _color = "#f00";
        }
        return new ol.style.Style({
            stroke: stroke,
            fill: fill,
            image: new ol.style.Circle({
                radius: 8,
                fill: new ol.style.Fill({
                    color: _color
                })
            }),
            text: new ol.style.Text({
                text: _name,
                textAlign: "left",
                offsetX: 12,
                font: "bold 13px sans-serif",
                fill: new ol.style.Fill({
                    color: 'red'
                }),
                stroke: new ol.style.Stroke({
                    color: 'white',
                    width: 2
                })
            })
        });
    }

    function getTilelayer(lyr) {
        var urls = [];
        for (var i = 0; i < 8; i++) {
            urls.push("http://t" + i + ".tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}&tk=16c5722fed64bcdbb390cc21a5548cf9");
        }
        var layer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                urls: urls
            })
        });
        return layer;
    }

</script>
</body>
</html>
